//
//  MianEightViewController.m
//  ShangPiBao
//
//  Created by chirui on 2017/10/23.
//  Copyright © 2017年 Shui. All rights reserved.
//

#import "MianEightViewController.h"
#import "GoodsDetailsViewController.h"
#import "CompanyListViewController.h"
#import "MainTableViewCell.h"
#import "ClassMessageViewController.h"
#import "CompanyMainDetailsVController.h"

@interface MianEightViewController ()<UITableViewDelegate,UITableViewDataSource,SDCycleScrollViewDelegate,UITextFieldDelegate>{
    
    UITableView * _tableView;
    NSArray * imageArray;
    NSArray * titleArray;
    NSArray * classIdArray;
    UITextField * searchText;
    
    NSArray * dataArray;
    NSDictionary * dataDic;
    
}

@property (nonatomic, strong) ImageTextButton * areButton;

@property (nonatomic, strong) ImageTextButton * searchButton;

@end

@implementation MianEightViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    TitleView(self.type);
    self.view.backgroundColor =[UIColor whiteColor];
    
//    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithIcon:@"icon_nav_return"  target:self action:@selector(backClick)];
    
     self.navigationItem.rightBarButtonItem = [UIBarButtonItem rightItemWithIcon:@"icon_tab_new_click" target:self action:@selector(messageBtn)];
    
    [self creatTableView];
    
    
    if ([self.type isEqualToString:@"酒店用品"]) {
        imageArray = @[@"icon_hotel_uniform",@"icon_hotel_kitchen",@"icon_hotel_lobby",@"icon_hotel_furniture",@"icon_hotel_clean",@"icon_hotel_cermet",@"icon_hotel_cookhouse",@"icon_costume_others"];
        titleArray = @[@"布草工服",@"客房用品",@"大堂用品",@"酒店家具",@"清洁用品",@"陶瓷玻璃",@"厨房用品",@"其他"];
        classIdArray = @[@"0,6,53",@"0,6,54",@"0,6,55",@"0,6,56",@"0,6,57",@"0,6,58",@"0,6,59",@"0,6,60"];
        
    }else if([self.type isEqualToString:@"文体办公"]){
        imageArray = @[@"icon_office_education",@"icon_office_sports",@"icon_office_computer",@"icon_office_work",@"icon_office_equipment",@"icon_office_consumable",@"icon_office_printing",@"icon_costume_others"];
        titleArray = @[@"文教用品",@"体育娱乐",@"电脑数码",@"办公用品",@"办公设备",@"办公耗材",@"广告印刷",@"其他"];
        classIdArray = @[@"0,5,93",@"0,5,94",@"0,5,95",@"0,5,96",@"0,5,97",@"0,5,98",@"0,5,99",@"0,5,100"];
        
    }else if([self.type isEqualToString:@"农林牧渔"]){
        imageArray = @[@"icon_forestry_manure",@"icon_forestry_pesticide",@"icon_forestry_seed",@"icon_forestry_supplies",@"icon_forestry_flowers",@"icon_forestry_farming",@"icon_forestry_produce",@"icon_costume_others"];
        titleArray = @[@"肥料",@"农药",@"种子",@"农用物资",@"苗木花卉",@"畜牧养殖",@"农产品",@"其他"];
        classIdArray = @[@"0,4,85",@"0,4,86",@"0,4,87",@"0,4,88",@"0,4,89",@"0,4,90",@"0,4,91",@"0,4,92"];
        
    }else if([self.type isEqualToString:@"服装鞋包"]){
        imageArray = @[@"icon_costume_man",@"icon_costume_woman",@"icon_costume_child",@"icon_costume_shoes",@"icon_costume_underwear",@"icon_costume_sports",@"icon_costume_pack",@"icon_costume_others"];
        titleArray = @[@"男装",@"女装",@"童装",@"鞋靴",@"内衣",@"运动户外",@"箱包配饰",@"其他"];
        classIdArray = @[@"0,3,109",@"0,3,110",@"0,3,111",@"0,3,112",@"0,3,113",@"0,3,114",@"0,3,115",@"0,3,116"];
    }else{
        imageArray = @[@"icon_logistics_guanzhong",@"icon_logistics_hanzhong",@"icon_logistics_ankang",@"icon_logistics_shangnuo",@"icon_logistics_yanan",@"icon_logistics_yulin",@"icon_logistics_provincial",@"icon_costume_others"];
        titleArray = @[@"关中地区",@"汉中地区",@"安康地区",@"商洛地区",@"延安地区",@"榆林地区",@"外省",@"其他"];
        classIdArray = @[@"0,1,77",@"0,1,78",@"0,1,79",@"0,1,80",@"0,1,81",@"0,1,82",@"0,1,83",@"0,1,84"];
    }
    
    [self getBannerDataListRequest];
}

-(void)backClick{
    
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)messageBtn{
    
    ClassMessageViewController * class =[[ClassMessageViewController alloc]init];
    if ([self.type isEqualToString:@"酒店用品"]){
        class.classId = @"0,6";
    }else if([self.type isEqualToString:@"文体办公"]){
        class.classId = @"0,5";
    }else if([self.type isEqualToString:@"农林牧渔"]){
        class.classId = @"0,4";
    }else if([self.type isEqualToString:@"服装鞋包"]){
        class.classId = @"0,3";
    }else{
        class.classId = @"0,1";
    }
    [self.navigationController pushViewController:class animated:YES];
    
}

-(void)searchClick:(UIButton *)btn{
     [searchText resignFirstResponder];
    if (searchText.text.length<=0||searchText.text==nil) {
        
        SHuiMBhudTextTimeStr(@"请输入关键字搜索");
        
        return;
    }
    CompanyListViewController * lists =[[CompanyListViewController alloc]init];
    if ([self.type isEqualToString:@"酒店用品"]){
        lists.classId = @"0,6";
        lists.bannerIdStr = @"0,6s";
    }else if([self.type isEqualToString:@"文体办公"]){
        lists.classId = @"0,5";
        lists.bannerIdStr = @"0,5s";
    }else if([self.type isEqualToString:@"农林牧渔"]){
        lists.classId = @"0,4";
        lists.bannerIdStr = @"0,4s";
    }else if([self.type isEqualToString:@"服装鞋包"]){
        lists.classId = @"0,3";
        lists.bannerIdStr = @"0,3s";
    }else{
        lists.classId = @"0,1";
        lists.bannerIdStr = @"0,1s";
    }
    lists.isSearch  = @"search";
    lists.titleStr = @"搜索列表";
    lists.searchStr = searchText.text;
    [self.navigationController pushViewController:lists animated:YES];
}

-(void)creatTableView{
    
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-64) style:UITableViewStyleGrouped];
    _tableView.dataSource =self;
    _tableView.delegate =self;
     _tableView.backgroundColor =[UIColor whiteColor];
    [self.view addSubview:_tableView];
    
    [_tableView registerNib:[UINib nibWithNibName:[MainTableViewCell reuseIdentifier] bundle:nil] forCellReuseIdentifier:[MainTableViewCell reuseIdentifier]];
    MJRefreshNormalHeader * header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [self getBannerDataListRequest];
        
    }];
    _tableView.mj_header =header;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if ([dataDic[@"position3"] isKindOfClass:[NSArray class]]) {
        
        dataArray = dataDic[@"position3"];
        
        return dataArray.count;
    }else{
        return 0;
    }

}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    float fourHeight = (WIDTH -50)/4 * 1.4;
    
    return 360 + fourHeight*2 +70 ;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 0.01;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 100;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSDictionary * dic = dataArray[indexPath.row];
    MainTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:[MainTableViewCell reuseIdentifier] forIndexPath:indexPath];
    cell.details.frame = CGRectMake(100, 38, WIDTH -110, 20);
    [cell.imageIcon sd_setImageWithURL:ImageUrl(dic[@"apicture"]) placeholderImage:ImageName(@"img_home_newest")];
    cell.details.text = dic[@"acontent"];
    cell.titleLabel.text = dic[@"atitle"];
    cell.details.numberOfLines = 3;
    [cell.details sizeToFit];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary * dic = dataArray[indexPath.row];
    if ([dic[@"aurl"] isEqualToString:@"0"]) {
        
    }else{
        CompanyMainDetailsVController * company =[[CompanyMainDetailsVController alloc]init];
        company.companyId = dic[@"aurl"];
        company.companyNameStr = dic[@"atitle"];
        company.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:company animated:YES];
    }
    
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView * heardView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
    heardView.backgroundColor =[UIColor whiteColor];
    
    NSMutableArray * bannerImageArray = @[].mutableCopy;
    NSMutableArray * bannerIdArray = @[].mutableCopy;
    
    if ([dataDic[@"position1"] isKindOfClass:[NSArray class]]) {
        
        if (bannerImageArray.count>0) {
            
             [bannerIdArray removeAllObjects];
            [bannerImageArray removeAllObjects];
        }
        NSArray * arry = dataDic[@"position1"];
        for (NSDictionary * dic in arry) {
            
            [bannerImageArray addObject:dic[@"apicture"]];
            [bannerIdArray addObject:dic];
        }
    }
    SDCycleScrollView *cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0,0, WIDTH, 160) delegate:self placeholderImage:[UIImage imageNamed:@""]];
    cycleScrollView.backgroundColor =Color(229, 229, 229);
    cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentRight;
    cycleScrollView.currentPageDotColor = [UIColor whiteColor];
    [heardView addSubview:cycleScrollView];
    cycleScrollView.autoScrollTimeInterval = 3.5;
    cycleScrollView.imageURLStringsGroup = bannerImageArray;
    if (bannerImageArray.count==1) {
        cycleScrollView.autoScroll = NO;
    }
    cycleScrollView.clickItemOperationBlock = ^(NSInteger index) {
        NSDictionary * dic = bannerIdArray[index];
        if ([dic[@"aurl"] isEqualToString:@"0"]) {
            
        }else{
            CompanyMainDetailsVController * company =[[CompanyMainDetailsVController alloc]init];
            company.companyId = dic[@"aurl"];
            company.companyNameStr = dic[@"atitle"];
            company.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:company animated:YES];
        }
 
    };
    
    self.areButton = [[ImageTextButton alloc] initWithFrame:CGRectMake(10, 7, 60,40 )
                                                      image:[UIImage imageNamed:@"icon_nav_drop_down"]
                                                      title:@"陕西"];
    self.areButton.buttonTitleWithImageAlignment = UIButtonTitleWithImageAlignmentRight;
    [heardView addSubview:self.areButton];
    
    
    self.searchButton = [[ImageTextButton alloc] initWithFrame:CGRectMake(WIDTH- 60, 16, 60,40 )
                                                         image:[UIImage imageNamed:@""]
                                                         title:@"搜索"];
    [self.searchButton addTarget:self action:@selector(searchClick:) forControlEvents:UIControlEventTouchUpInside];
    [heardView addSubview:self.searchButton];
    
    UIView * searchView =[[UIView alloc]initWithFrame:CGRectMake(75, 10, WIDTH - 150, 30)];
    searchView.layer.cornerRadius = 15.f;
    searchView.layer.masksToBounds = YES;
    
    UIImageView * searchImage =[[UIImageView alloc]initWithFrame:CGRectMake(10, 0, 30, 30)];
    searchImage.image =[UIImage imageNamed:@"icon_nav_search"];
    [searchView addSubview:searchImage];
    searchView.backgroundColor = ColorA(255, 255, 255, 0.7);
    
    searchText =[[UITextField alloc]initWithFrame:CGRectMake(40, 0, CGRectGetWidth(searchView.frame)-40, 30)];
    searchText.font =[UIFont systemFontOfSize:14];
    searchText.delegate = self;
    searchText.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入产品或者公司名称" attributes:@{NSForegroundColorAttributeName: [UIColor grayColor]}];
    [searchView addSubview:searchText];
    [heardView addSubview:searchView];
    
    CGFloat imageWide = 60;
    CGFloat gapWide = (WIDTH - 60*4)/5;
    
    float fourWidth = (WIDTH -50)/4;
    float fourHeight = (WIDTH -50)/4 * 1.4;
    
    UIView * classView =[[UIView alloc]initWithFrame:CGRectMake(0,160, WIDTH, 180)];
    classView.backgroundColor = [UIColor whiteColor];
    [heardView addSubview:classView];
    
    for (int i = 0; i < 8; i++) {
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        
        btn.frame = CGRectMake(gapWide+gapWide*(i%4)+imageWide*(i % 4), 10+10 *(i/4)+(imageWide+15)*(i/4) , imageWide, imageWide);
        btn.tag = 100 + i;
        btn.layer.cornerRadius = 30.f;
        btn.layer.masksToBounds = YES;
        [btn setImage:[UIImage imageNamed:imageArray[i]] forState:UIControlStateNormal];
        btn.backgroundColor =[UIColor whiteColor];
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [classView addSubview:btn];
        
        UILabel *label = [[UILabel alloc]init];
        label.center = CGPointMake(btn.center.x, btn.center.y + imageWide / 2.f +10);
        label.bounds = CGRectMake(0, 0, 100, 13);
        label.font = [UIFont systemFontOfSize:13];
        label.textColor = [UIColor blackColor];
        label.textAlignment = NSTextAlignmentCenter;
        label.text = titleArray[i];
        [classView addSubview:label];
    }
    
    UIView * lineView =[[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(classView.frame), WIDTH, 10)];
    lineView.backgroundColor =[UIColor groupTableViewBackgroundColor];
    [heardView addSubview:lineView];
    
    
    UIView * fourView;
    
    NSArray * eightArray;
    if ([dataDic[@"position2"] isKindOfClass:[NSArray class]]) {
        
        eightArray = dataDic[@"position2"];
    }
    if (eightArray.count >0) {

    for (int g = 0; g<eightArray.count; g++) {
          NSDictionary * dic = eightArray[g];
        fourView = [self creatBtnViewFrame:CGRectMake(10+fourWidth*(g%4)+10*(g%4), CGRectGetMaxY(classView.frame)+20 + (fourWidth+15)*(g/4) + 20*(g/4), fourWidth, fourHeight) andBorderColor:[UIColor clearColor] onView:heardView];
        fourView.layer.borderWidth = 0.5;
        [fourView tapAction:^{
            if ([dic[@"aurl"] isEqualToString:@"0"]) {
                
            }else{
                CompanyMainDetailsVController * company =[[CompanyMainDetailsVController alloc]init];
                company.companyId = dic[@"aurl"];
                company.companyNameStr = dic[@"atitle"];
                company.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:company animated:YES];
            }

        }];
        fourView.layer.borderColor = RGB(0xe5e5e5).CGColor;
        
        [self creatLaberFrame:CGRectMake(0,8, fourWidth, 18) andFontOfSize:14 andTextColor:RGB(0x4c4c4c) andText:dic[@"atitle"] andAlignment:NSTextAlignmentCenter onView:fourView];
        
        [self creatLaberFrame:CGRectMake(0,26, fourWidth, 15) andFontOfSize:12 andTextColor:[UIColor orangeColor] andText:dic[@"acontent"] andAlignment:NSTextAlignmentCenter onView:fourView];
        
        UIImageView * heardImage =[[UIImageView alloc]initWithFrame:CGRectMake(4, 43,fourWidth-8 ,fourHeight -43)];
        heardImage.backgroundColor = [UIColor whiteColor];
        [heardImage sd_setImageWithURL:ImageUrl(dic[@"apicture"]) placeholderImage:ImageName(@"img_home_newest")];
        [fourView addSubview:heardImage];
       }
     }
    UIView * lineSecondView =[[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(fourView.frame)+10, WIDTH, 10)];
    lineSecondView.backgroundColor =[UIColor groupTableViewBackgroundColor];
    [heardView addSubview:lineSecondView];
    
    UILabel * titleLabel =[[UILabel alloc]initWithFrame:CGRectMake(10, CGRectGetMaxY(lineSecondView.frame)+15, WIDTH - 20, 20)];
    titleLabel.text = @"最新商户";
    [heardView addSubview:titleLabel];
    
    return heardView;
}

-(UIView *)creatBtnViewFrame:(CGRect)rec andBorderColor:(UIColor *)col onView:(UIView *)view {
    
    UIView * btnView =[[UIView alloc]init];
    btnView.frame = rec;
    btnView.layer.borderWidth = 0.7f;
    btnView.layer.borderColor = col.CGColor;
    btnView.backgroundColor =[UIColor whiteColor];
    //    btnView.layer.cornerRadius = 5.f;
    //    btnView.layer.masksToBounds =YES;
    [view addSubview:btnView];
    
    return btnView;
}

-(void)creatLaberFrame:(CGRect)rec andFontOfSize:(float)size andTextColor:(UIColor*)col andText:(NSString *)text andAlignment:(NSTextAlignment )ment onView:(UIView *)view {
    
    UILabel * label =[[UILabel alloc]initWithFrame:rec];
    label.font = [UIFont systemFontOfSize:size];
    label.textColor =col;
    label.textAlignment = ment;
    label.text = text;
    [view addSubview:label];
}

-(void)btnClick:(UIButton *)btn {
    
    CompanyListViewController * lists =[[CompanyListViewController alloc]init];
    lists.classId = classIdArray[btn.tag-100];
    lists.bannerIdStr = classIdArray[btn.tag-100];
    lists.titleStr = titleArray[btn.tag -100];
    [self.navigationController pushViewController:lists animated:YES];
    
}

-(void)getBannerDataListRequest{
    
    NSString * md5ver = [SHJudgeTools md532BitLower:[NSString
                                                     stringWithFormat:@"%@api.shangpibao.com",USER_DEFAULTGet(@"phone")]];
    NSString * parametersStr = [NSString stringWithFormat:@"%@%@?uphone=%@&ver=%@&aclass=%@&page=1",address_url,new_allNews_api,USER_DEFAULTGet(@"phone"),md5ver,self.classIdStr];
    
    [PostNetWorking netWorkingStr:parametersStr  Success:^(id responseObject) {
        SHuiMBHidleYes;
        if ([responseObject[@"err"] intValue]==0) {
            
            dataDic = responseObject;
            
        } else {
            
            SHuiMBhudTextTimeStr(EorrMessageStr);
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [_tableView.mj_header endRefreshing];
            [_tableView reloadData];
            
        });
        
    } failed:^(NSError *error) {
        
        SHuiMBHidleYes;
        SHuiMBhudTextTimeStr(@"请检查您的网络!");
    }];
    
}

@end
